package com.itheima.leyou.controller;

import com.itheima.leyou.dto.UserDTO;
import com.itheima.leyou.dto.UserDetail;
import com.itheima.leyou.entity.User;
import com.itheima.leyou.service.UserService;
import com.itheima.leyou.utils.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/info")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 根据用户名和密码查询
     *
     * @param username
     * @param password
     * @return
     */
    @GetMapping
    public ResponseEntity<UserDTO> loginUser(
            @RequestParam("username")String username,
            @RequestParam("password")String password){
        return ResponseEntity.ok(userService.loginUser(username,password));

    }


    /**
     * 用户注册
     * @param user
     * @param code
     * @return
     * @Valid 用于验证注解是否符合要求
     */
    @PostMapping
    public ResponseEntity<Void> registry(
            @Valid User user,
            @RequestParam("code")String code){
        this.userService.registry(user,code);
        return ResponseEntity.status(HttpStatus.CREATED).build();

    }


    /**
     * 发送短信验证码
     * @param phone
     * @return
     */
    @PostMapping("/code")
    public ResponseEntity<Void> sendMgs(
            @RequestParam("phone")String phone){
        userService.sendMgs(phone);
        return ResponseEntity.status(HttpStatus.CREATED).build();

    }


    /**
     * 判断信息是否存在
     * @param data
     * @param type
     * @return
     */
    @GetMapping("/exists/{data}/{type}")
    public ResponseEntity<Boolean> isExists(
            @PathVariable("data")String data,
            @PathVariable("type")Integer type){
       Boolean flag =  userService.isExists(data,type);
        return ResponseEntity.ok(flag);
    }


    /**
     * 校验用户信息
     * @return
     */
    @GetMapping("/me")
    public ResponseEntity<UserDetail> checkLogin(){
        return ResponseEntity.ok(UserContext.getUser());
    }

}
